﻿using UnityEngine;

namespace CWM.Skinn
{
	public static partial class SkinnEx
    {
        public static Vector3 MidPoint(this Vector3 startPoint, Vector3 endPoint)
        {
            return startPoint.PercentagePoint(endPoint, 2, 3);
        }

        public static Vector3 PercentagePoint(this Vector3 startPoint, Vector3 endPoint, int point, int totalCount)
        {
            int t = Mathf.Abs(totalCount);
            int p = Mathf.Clamp(point, 0, t);
            float midX = startPoint.x + ((endPoint.x - startPoint.x) / t * p);
            float midY = startPoint.y + ((endPoint.y - startPoint.y) / t * p);
            float midZ = startPoint.z + ((endPoint.z - startPoint.z) / t * p);
            return new Vector3(midX, midY, midZ);
        }

        //https://forum.unity.com/threads/math-problem.8114/#post-59715
        public static float DistanceToEdge(Vector3 a, Vector3 b, Vector3 c)
        {
            Vector3 a1 = c - a;
            Vector3 a2 = (b - a).normalized;
            float distance = Vector3.Distance(a, b);
            float dot = Vector3.Dot(a2, a1);
            if (dot <= 0) return Vector3.Distance(a, c);
            if (dot >= distance)
                return Vector3.Distance(b, c);
            Vector3 c1 = a2 * dot;

            return Vector3.Distance(a + c1, c);
        }

        public static float DistanceToPointOnLine(Vector3 origin, Vector3 direction, Vector3 point)
        {
            Vector3 point2origin = origin - point;
            Vector3 point2closestPointOnLine = point2origin - Vector3.Dot(point2origin, direction) * direction;
            return point2closestPointOnLine.magnitude;
        }

        public static float DistanceToInfiniteLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
        {
            Vector3 p12 = new Vector3(lineEnd.x - lineStart.x, lineEnd.y - lineStart.y, lineEnd.z - lineStart.z);
            Vector3 p10 = new Vector3(point.x - lineStart.x, point.y - lineStart.y, point.z - lineStart.z);
            return Vector3.Cross(p10, p12).magnitude / p12.magnitude;
        }
    }
}